using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
using System.IO;

using System.Data;

using Pampa.Grid.Utils;

using Pampa.Grid.Core;
using Pampa.Grid.Data;
using Pampa.Grid.UI.Exceptions;
using Pampa.Grid.Exceptions;
using Pampa.Grid.Core.Filters;

using Pampa.WebControls;

using Pampa.CRUD.UI.CustomControls;
using Pampa.CRUD.Configuration;

namespace Pampa.Grid.UI.CustomControls
{
    [DesignerAttribute(typeof(BaseDesigner), typeof(System.ComponentModel.Design.IDesigner))]
    public class QuickFiltersPanel : BaseControl
    {
        private string gridID;
        private string filerButtonIcon;
        private string cleanFilerButtonIcon;
        private string pathImages;
        private List<ClientButton> buttons;
        private CustomGrid customGrid;
        private Dictionary<string, Control> controls;

        public QuickFiltersPanel()
        {
            this.CssClass = "quickFiltersDefault";
            this.FilerButtonIcon = "Pampa.Common" + GetImagesPath() + "/filters.gif";
            this.CleanFilerButtonIcon = "Pampa.Common" + GetImagesPath() + "/trash2.png";
            this.clientClass = "QuickFiltersPanel";

            buttons = new List<ClientButton>();
            controls = new Dictionary<string, Control>();
        }

        #region Properties

        public string GridID
        {
            get { return gridID; }
            set { gridID = value; }
        }

        public string FilerButtonIcon
        {
            get { return filerButtonIcon; }
            set { filerButtonIcon = value; }
        }

        public string CleanFilerButtonIcon
        {
            get { return cleanFilerButtonIcon; }
            set { cleanFilerButtonIcon = value; }
        }

        public string PathImages
        {
            get { return pathImages; }
            set { pathImages = value; }
        }

        public List<ClientButton> Buttons
        {
            get { return buttons; }
        }

        public CustomGrid Grid
        {
            get 
            {
                if (customGrid == null && this.Page != null)
                {
                    customGrid = (CustomGrid)Page.FindControl(this.GridID);
                }

                if (customGrid == null)
                {
                    throw (new CustomGridException("QuickFiltersPanel Error. There is no CustomGrid associated to the panel.'"));
                }

                return customGrid;
            }
            set
            {
                customGrid = value;
                this.GridID = customGrid.ID;
            }
        }

        #endregion

        #region Load

        protected override void OnLoad(EventArgs e)
        {
            if (this.CssClass == "quickFiltersDefault")
                RegisterStyleSheet("Pampa.Grid/QuickFiltersPanel.css");

            RegisterLibrary("Pampa.Common/Common.js");
            RegisterLibrary("Pampa.CRUD/ItemsCommon.js");
            RegisterLibrary("Pampa.Grid/QuickFiltersPanel.js");

            base.OnLoad(e);
        }

        #endregion

        #region Render

        protected override void Render(HtmlTextWriter writer)
        {
            foreach (QuickFilterDefinition qfItem in this.Grid.QuickFilterDefinitions)
            {
                this.Controls.Add(GetControl(qfItem.Item));
            }

            base.Render(writer);
            RenderDefinitions(writer);
        }

        /// <summary>
        /// Construyo el objeto cliente que representa al combo
        /// </summary>
        private void RenderDefinitions(HtmlTextWriter output)
        {
            string objectName = "obj" + this.ID;

            output.WriteLine("<script type=\"text/javascript\">");
            output.WriteLine("var " + objectName + " = new " + this.clientClass + "(\"" + this.ID + "\", \"" + this.GridID + "\");");

            if(!String.IsNullOrEmpty(this.Grid.QuickFilterMethod))
                output.WriteLine(objectName + ".externalFilterMethod = \"" + this.Grid.QuickFilterMethod + "\";");

            foreach (QuickFilterDefinition qfItem in this.Grid.QuickFilterDefinitions)
            {
                string field = qfItem.Field;
                string itemID = qfItem.Item.Id;
                string controlID = GetControlId(qfItem.Item.Id);
                string controlType = ((int)qfItem.Item.ItemType).ToString();
                string operationType = Enum.GetName(typeof(OperationType), qfItem.OperationType);
                string valueType = qfItem.ValueType.AssemblyQualifiedName;

                output.WriteLine(objectName + ".addItem('" + itemID + "','" + field + "','" + controlID + "'," + controlType + ",'" + operationType + "','" + valueType + "');");
            }

            output.WriteLine("</script>");
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            if (this.Grid == null)
            {
                output.WriteLine("There is no grid called " + this.GridID);
            }
            else
            {
                output.WriteLine("<table style=\"width:100%\">");
                output.WriteLine("<tr><td><table>");

                output.WriteLine("<tr>");

                // labels
                foreach (QuickFilterDefinition qfItem in this.Grid.QuickFilterDefinitions)
                {
                    output.WriteLine("<td class=\"label\">");
                    output.WriteLine(qfItem.Item.Label);
                    output.WriteLine("</td>");
                }

                // buttons

                output.WriteLine("<td>&nbsp;</td>");

                output.WriteLine("</tr>"); 
                output.WriteLine("<tr>");

                // controls
                foreach (QuickFilterDefinition qfItem in this.Grid.QuickFilterDefinitions)
                {
                    output.WriteLine("<td style=\"text-align:left; vertical-align:middle;\" class=\"quickFiltersCell\">");

                    // recupero el valor del quickfilter aplicado actualmente a la grilla
                    qfItem.Item.Value = GetFilterValue(qfItem.Field, qfItem.OperationType);

                    Control control = GetControl(qfItem.Item);
                    control.RenderControl(output);

                    output.WriteLine("</td>");
                }

                RenderButtons(output);

                output.WriteLine("</tr>");
                output.WriteLine("</table></tr></td>");
                output.WriteLine("</table>");
            }
        }

        private void RenderButtons(HtmlTextWriter output)
        {
            output.WriteLine("<td style=\"text-align:center; vertical-align:middle\">");
            output.WriteLine("<table border=\"0\">");
            output.WriteLine("<tr>");

            // Filter Button
            output.WriteLine("<td style=\"padding:5px\">");
            ClientButton btnFilter = GetFilterButton();
            btnFilter.RenderControl(output);
            output.WriteLine("</td>");

            // Clean Button
            output.WriteLine("<td style=\"padding:5px\">");
            ClientButton btnClean = GetCleanButton();
            btnClean.RenderControl(output);
            output.WriteLine("</td>");

            // Rest of buttons
            foreach (ClientButton button in this.Buttons)
            {
                output.WriteLine("<td style=\"padding:5px\">");
                button.RenderControl(output);
                output.WriteLine("</td>");
            }

            output.WriteLine("</tr>");
            output.WriteLine("</table>");
            output.WriteLine("</td>");
        }

        #endregion

        #region Private Functions

        private string GetControlId(string itemID)
        {
            if (String.IsNullOrEmpty(itemID))
                return "";
            else
                return this.ID + "_" + itemID;
        }

        private ClientButton GetFilterButton()
        {
            ClientButton btnFilter = new ClientButton();
            btnFilter.ID = this.GetControlId("btnFilter");
            btnFilter.Type = Pampa.WebControls.ButtonType.Image;
            btnFilter.IconPath = this.FilerButtonIcon;
            btnFilter.MethodName = "QuickFiltersPanel_Filter('" + this.ID + "')";
            btnFilter.CssClass = "iconButton";
            btnFilter.Text = Resources.CustomGrid.FilterApply;

            return btnFilter;
        }

        private ClientButton GetCleanButton()
        {
            ClientButton btnClean = new ClientButton();
            btnClean.ID = this.GetControlId("btnClean");
            btnClean.Type = Pampa.WebControls.ButtonType.Image;
            btnClean.IconPath = this.CleanFilerButtonIcon;
            btnClean.MethodName = "QuickFiltersPanel_Clean('" + this.ID + "')";
            btnClean.CssClass = "iconButton";
            btnClean.Text = Resources.CustomGrid.CleanFilter;

            return btnClean;
        }

        private Control GetControl(EditItem item)
        {
            Control control = controls.ContainsKey(item.Id) ? controls[item.Id] : null;

            if (control == null)
            {
                control = item.Control;
                control.ID = GetControlId(item.Id);

                if (item is EntityComboItem)
                {
                    EntityComboItem entityComboItem = (EntityComboItem) item;
                    EntityComboList entityComboList = (EntityComboList) control;
                    entityComboList.ParentId = GetControlId(entityComboItem.ParentId);

                    if (!String.IsNullOrEmpty(this.PathImages))
                        entityComboList.PathImages = this.PathImages;
                }
                else if (item is EntitySelectorItem)
                {
                    EntitySelectorItem selectorItem = (EntitySelectorItem) item;
                    EntitySelector entitySelector = (EntitySelector) control;
                    entitySelector.ParentId = GetControlId(selectorItem.ParentId);
                }
                else if (item is EntityCheckListItem)
                {
                    EntityCheckListItem entityCheckListItem = (EntityCheckListItem) item;
                    EntityCheckList entityCheckList = (EntityCheckList) control;
                    entityCheckList.ParentId = GetControlId(entityCheckListItem.ParentId);

                    if (!String.IsNullOrEmpty(this.PathImages))
                        entityCheckList.PathImages = this.PathImages;
                }
                else if (item is StaticComboItem)
                {
                    ComboList comboList = (ComboList) control;

                    if (!String.IsNullOrEmpty(this.PathImages))
                        comboList.PathImages = this.PathImages;
                }
                else if (item is DateCombosItem)
                {
                    DatePickerCombos datePickerCombos = (DatePickerCombos) control;

                    if (!String.IsNullOrEmpty(this.PathImages))
                        datePickerCombos.PathImages = this.PathImages;
                }
            }

            return control;
        }

        private object GetFilterValue(string field, OperationType operationType)
        {
            foreach (Filter filter in this.Grid.Configuration.QuickFilter.InnerFilters)
            {
                if (filter is SimpleFilter)
                {
                    SimpleFilter simpleFilter = (SimpleFilter)filter;
                    if ((simpleFilter.Field == field) && (simpleFilter.Operation == operationType))
                    {
                        return simpleFilter.Value;
                    }
                }
            }

            return null;
        }

        #endregion
    }

}